<?php

namespace App\Repositories;

use App\Models\Role;
use App\Models\RoleMenu;
use App\Exceptions\InvalidException;
use DB;

class RoleRepo
{
	public function getAll()
	{
		return Role::with(['access'=>function($query){
			
		},
		'menus'=>function($query) {

		}
	])->get()->toArray();
	}
	public function createRole(array $data) 
	{
		$role = new Role();
		$role->name = $data['name'];
		$role->save();
	}
	public function updateRole($id,array $data) 
	{
		$role = Role::where('id',$id)->first();
		
		$role->name = $data['name'];
		$role->save();
	}
	public function saveMenus($role_id,array $data) 
	{
		DB::beginTransaction();

		try{
			RoleMenu::where('role_id',$role_id)->delete();
			$main_data = [];
			foreach($data as $menu_id) {
				$main_data[] = [
					'role_id' => $role_id,
					'menu_id' => $menu_id
				];
			}
			RoleMenu::insert($main_data);
			DB::commit();
		}catch(\Exception $e) {
			DB::rollback();
			throw new InvalidException($e->getMessage());
		}
	}
}